package com.guyaogg.gulimall.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 自定义 RedisCacheConfiguration ，实现 json 序列化
 *
 * @author 顾遥
 */
@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)
public class MyCacheConfig {

    /**
     * # @ConfigurationProperties(prefix = "spring.cache")
     * # public class CacheProperties
     *  要让他生效 @EnableConfigurationProperties()
     * @param cacheProperties
     * @return
     */
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        // 拿取配置文件的
        CacheProperties.Redis redisProperties = cacheProperties.getRedis();

        // 在默认基础上修改
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        // 改过覆盖
        // 改序列化机制
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        // 随机时间不知道能不能成功,,不行哈，写的还是固定的
//        config = config.entryTtl(Duration.ofHours((long) (Math.random() * 24 + 1)));

        // 将配置文件中的配置都生效

        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }

        if (redisProperties.getKeyPrefix() != null) {
            // prefixCacheNameWith(String) : 在 key 前面加上前缀（标识） prefixKeysWith(String)：把 key 前面的分区名取代掉（统一分区
            config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
        }

        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }

        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }
        return config;
    }
}
